using System.Security.Claims;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Crossborder.Common.EventBusHelper;
using Crossborder.Common.Utility;
using Crossborder.Core;
using Crossborder.Core.Const;
using Crossborder.Core.Repository;
using Crossborder.Extensions;
using Crossborder.Service.Base;
using Crossborder.Web.MinimalApi;
using Microsoft.EntityFrameworkCore;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
var config = builder.Configuration;
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Crossborder.Web", Version = "v1" });
    // 添加安全定义
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "格式：Bearer {token}",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    // 添加安全要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme {
                Reference = new OpenApiReference{
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                },
            }, new string[] {}
        }
    });
});
builder.Services.AddCors(opt => opt.AddPolicy("Any", p => p.WithOrigins("localhost:5666").AllowAnyHeader().AllowAnyMethod()));
builder.Services.AddDbContext<CrossborderDbContext>(options =>
{
    options.UseSqlServer(config.GetConnectionString("Default"));
});
builder.Services.AddSingleton(new Appsettings(builder.Configuration));
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
builder.Services.AddScoped(typeof(LocalEventBus<>));
builder.Services.AddAutoMapper(typeof(CrossBorderProfile));
builder.Services.AddAuthorizationForJWT(builder.Configuration);
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy(AuthorizationConst.ADMIN, p =>
    {
        // p.AddAuthenticationSchemes().RequireAssertion(ass => ass.User.HasClaim(c => c.Type == ClaimTypes.Role) && ass.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == AuthorizationConst.ADMIN);  // 鉴权方案绑定授权
        p.RequireAssertion(ass => ass.User.HasClaim(c => c.Type == ClaimTypes.Role) && ass.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == AuthorizationConst.ADMIN);
    });
    options.AddPolicy(AuthorizationConst.USER, p =>
    {
        p.RequireAssertion(ass => ass.User.HasClaim(c => c.Type == ClaimTypes.Role) && (ass.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == AuthorizationConst.ADMIN || ass.User.Claims.First(c => c.Type.Equals(ClaimTypes.Role)).Value == AuthorizationConst.USER));
    });
});

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(options =>
{
    options.RegisterModule<AutofacExtension>();
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors("Any");
app.UseMinimalApiExtension();
app.UseHttpsRedirection();
app.Run();
